package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.GoldInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.StringConvertNumber;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.DialogWidget;
import com.haotunet.app.goldtreasure.views.PayPasswordView;
import com.haotunet.app.goldtreasure.views.PayPasswordView.OnPayListener;
import com.haotunet.app.goldtreasure.views.TitleView;

public class CurrentTransferActivity extends BaseActivity {
    private TitleView mTitleView;
    private TextView mCurrentGold;
    private EditText etGrams;
    private Button mTransBtn;
    private String transGram;
    private TextView tvTransTo;
    private String current_gold;
    private DialogWidget mDialogWidget;
    private GoldInfo goldInfo;
    private final int GET_CURRENT_GOLD_INFO_SUCCESS = 2;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GET_CURRENT_GOLD_INFO_SUCCESS:
                    goldInfo = (GoldInfo) msg.obj;
                    current_gold = goldInfo.getAvailableGold();
                    mCurrentGold.setText(current_gold);
                    break;

                default:
                    break;
            }
        }

    };
    private String regularId;
    private PayPasswordView passwordView;
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_transfer);
        shareStore = new ShareStore(CurrentTransferActivity.this);
        initView();
        initData();
    }

    private void initData() {
        getMyCurrentGoldInfo();
    }

    private void getMyCurrentGoldInfo() {
        ActionUtil actionUtil = new ActionUtil(CurrentTransferActivity.this);
        actionUtil.getMyCurrentGold(regularId);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                GoldInfo goldInfo = (GoldInfo) model;
                if (goldInfo == null) {
                    UIHelper.showToast(CurrentTransferActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (goldInfo.getErrorMsg() != null) {
                    if (goldInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(CurrentTransferActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(CurrentTransferActivity.this, goldInfo.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = GET_CURRENT_GOLD_INFO_SUCCESS;
                    msg.obj = goldInfo;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void initView() {
        String productName = getIntent().getStringExtra("productName");
        regularId = getIntent().getStringExtra("regularId");
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText("转入");
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mCurrentGold = (TextView) findViewById(R.id.txt_current_gold_grams);
        tvTransTo = (TextView) findViewById(R.id.txt_trans_to);
        tvTransTo.setText("流动金转入" + productName);
        etGrams = (EditText) findViewById(R.id.et_trans_grams);
        if (productName.contains("稳健金")) {
            etGrams.setHint("最低转入10克");
        }
        addEditextListener();
        mTransBtn = (Button) findViewById(R.id.btn_sure_trans);
        mTransBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                transGram = etGrams.getText().toString();
                if (TextUtils.isEmpty(transGram)) {
                    UIHelper.showToast(CurrentTransferActivity.this, "请输入转入的克数!");
                    return;
                }
                if (goldInfo.getJudgingCondition() == 1) {
                    if (Double.parseDouble(transGram) < Double.parseDouble(goldInfo.getInvestmentBaseline())) {
                        UIHelper.showToast(CurrentTransferActivity.this, "最低转入" + goldInfo.getInvestmentBaseline() + "克");
                        return;
                    }
                } else if (goldInfo.getJudgingCondition() == 2) {
                    if (Double.parseDouble(transGram) > Double.parseDouble(goldInfo.getInvestmentBaseline())) {
                        UIHelper.showToast(CurrentTransferActivity.this, "最高转入" + goldInfo.getInvestmentBaseline() + "克");
                        return;
                    }
                }
                mDialogWidget = new DialogWidget(CurrentTransferActivity.this, getDecorViewDialog());
                mDialogWidget.show();
            }
        });
        closeTransBtn();
    }

    private void addEditextListener() {
        etGrams.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 3) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 4);
                        etGrams.setText(inputString);
                        etGrams.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".")) {
                    inputString = "0";
                    etGrams.setText(inputString);
                    etGrams.setSelection(1);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        etGrams.setText(inputString.subSequence(1, 2));
                        etGrams.setSelection(1);
                        return;
                    }
                }
                if (inputString.length() > 0) {
                    double inputGram = StringConvertNumber.parseDouble(inputString);
                    double amountGram = StringConvertNumber.parseDouble(current_gold);
                    if (inputGram == 0) {
                        closeTransBtn();
                    } else if (inputGram > amountGram) {
                        closeTransBtn();
                    } else {
                        openTransBtn();
                    }
                } else {
                    closeTransBtn();
                }
            }
        });
    }

    private void currentToRegular(String tradePwd) {

        ActionUtil actionUtil = new ActionUtil(CurrentTransferActivity.this);
        actionUtil.currentToRegular(transGram, regularId, tradePwd);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(CurrentTransferActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(CurrentTransferActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        passwordView.clearUi();
                        UIHelper.showToast(CurrentTransferActivity.this, model.getErrorMsg());
                    }

                } else {
                    if ("false".equals(model.getStatus())) {
                        passwordView.clearUi();
                        passwordView.setErrorTip(model.getInfo());
                    } else {
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    Intent intent = new Intent();
                                    intent.setClass(CurrentTransferActivity.this, TransRecordActivity.class);
                                    intent.putExtra("type", "transSuccess");
                                    startActivity(intent);
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;
                                    CurrentTransferActivity.this.finish();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            getMyCurrentGoldInfo();
        }
    }

    protected View getDecorViewDialog() {
        if (shareStore.getInt(Strs.IS_HAD_TRADING_PWD, 0) == 1) {
            passwordView = new PayPasswordView(2, 2, CurrentTransferActivity.this, null, "", null);
        } else {
            passwordView = new PayPasswordView(1, 2, CurrentTransferActivity.this, null, "", null);
        }
        passwordView.setOnPayListener(new OnPayListener() {

            @Override
            public void onSurePay(String password) {
                currentToRegular(password);
            }

            @Override
            public void onCancelPay() {
                mDialogWidget.dismiss();
                mDialogWidget = null;
            }
        });
        return passwordView.getView();
    }

    private void openTransBtn() {
        mTransBtn.setBackgroundResource(R.drawable.login_btn_bg_formal);
        mTransBtn.setEnabled(true);
    }

    private void closeTransBtn() {
        mTransBtn.setBackgroundResource(R.drawable.login_btn_bg_unclick);
        mTransBtn.setEnabled(false);
    }
}
